import Vue from "vue";
import VueRouter from "vue-router";
import Login from "../components/Login/Login"
import Home from "../components/home/home"
import Mine from "../components/Mine/Mine"
import Search from "../components/Search/Search"
import Rec from "../components/Rec/Rec"
import SearchHot from "../components/SearchHot/SearchHot"
import SearchResult from "../components/SearchResult/SearchResult"
import SearchAdv from "../components/SearchAdv/SearchAdv"
Vue.use(VueRouter)

const router = new VueRouter({
    routes: [
        { path: '/', redirect: '/login', meta: { title: '微音乐首页' } },
        { path: '/login', component: Login, meta: { title: '微音乐登录' } },
        {
            path: '/home',
            redirect: '/home/rec',
            component: Home,
            meta: { title: '微音乐首页' },
            children: [
                { path: 'rec', component: Rec, meta: { title: '微音乐推荐' } },
                {
                    path: 'search',
                    component: Search,
                    redirect:'search/searchhot',
                    meta: { title: '微音乐搜索' },
                    children:[
                        {path:'searchhot',component:SearchHot,meta: { title: '热门搜索' }},
                        {path:'searchadv',component:SearchAdv,meta: { title: '搜索建议' }},
                        {path:'searchresult',component:SearchResult,meta: { title: '搜索结果' }}
                    ],
                },
                { path: 'mine', component: Mine, meta: { title: '我的微音乐' } },

            ],
            beforeEnter: (to, from, next) => {
                fetch(
                    `http://localhost:3000/login/status?cookie=${localStorage.getItem('cookie')}`,
                    {
                        methods: 'post'
                    }
                ).then(r => r.json())
                    .then(res => {
                        console.log(res)
                        if (res.data.account.id) {
                            next()
                        }
                        else {
                            next({ path: '/login' })
                        }
                    })
            }
        },
    ]
})


router.beforeEach((to, from, next) => {
    if (to.meta.title) {
        // 路由守卫
        document.title = to.meta.title
        next()
    }
})
export default router